<?php

namespace app\api\controller\worker;

use app\api\controller\Base;
use app\common\model\worker\OfferModel;
use think\facade\Db;

class OfferController extends Base
{
    private $model;
    /**
     * 构造方法
     * @access public
     * @throws \Exception
     */
    public function __construct()
    {
        parent::__construct();
        $this->checkLogin();
        $this->model = new OfferModel();
    }

    /**
     * 报价单列表
     */
    public function index(){
        $pageSize      = $this->request->param('pageSize/d', 20); //每页多少条
        $pageNumber    = $this->request->param('pageNumber/d'); //当前页
        $sortName      = $this->request->param('sortName','id'); //排序字段
        $sortOrder     = $this->request->param('sortOrder', 'desc'); //升序降序
        $order         = !empty($sortName) ? "{$sortName} {$sortOrder}" : '';//排序
        $query = [];
        $customerId = $this->request->param('customer_id');
        $offerStatus = $this->request->param('offer_status');
        if(!empty($customerId)){
            $query[] = ['customer_id','=',$customerId];
        }
        if($offerStatus==0) $query[] = ['order_id','=',0];
        if($offerStatus==1) $query[] = ['order_id','>',0];
        $data          = ['total' => 0, 'rows' => []];
        $tempSql =$this->model->group('offer_sn')->buildSql();
        $data['total'] =  Db::table($tempSql.' temp')->where($query)->count();
        if ($data['total'] > 0) {
            $rows =  Db::table($tempSql.' temp')
                ->where($query)
                ->page($pageNumber,$pageSize)
                ->order($order)
                ->select()
                ->toArray();
            $rows = $this->model->_formatList($rows);
            $data['rows'] = $rows;
            $data['order'] = $order;
        }
        $this->result($data);

    }

    /**
     * 添加报价单
     */
    public function addOffer(){
        $data = $this->request->param();
        $this->validate($data,[
            'customer_id|客户'=>'require',
            'offer_data|报价数据'=>'require',
        ]);
        //$data['offer_data'] = json_decode($data['offer_data'],true);
        $info = $this->model->addOffer($data,$this->loginInfo['id']);
        $this->result($info);
    }

    /**
     * 报价单数据
     */
    public function offerInfo(){
        $offerSn = $this->request->param('offer_sn');
        $info = $this->model->getOffer($offerSn);
        $this->result($info);
    }

    public function delOffer(){
        $id = $this->request->param('id');
        $this->model->del($id);
        $this->result();
    }

    /**
     * 报价单转为订单
     */
    public function changeOrder(){
        $offerSn = $this->request->param('offer_sn');
        $discountAmount = $this->request->param('discount_amount');
        $info = $this->model->changeOrder($offerSn,$discountAmount);
        $this->result($info);
    }
}
